package com.allwees.bs.module.oms.dao;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.allwees.bs.core.model.order.wf.order.EOrderItemState;
import com.allwees.bs.core.model.order.wf.refund.ERefundState;
import com.allwees.bs.module.oms.entity.OrderItem;
import com.allwees.core.dao.mybatis.dao.BaseDao;
import org.apache.ibatis.annotations.Select;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @author yangylsky
 * @since 2019-08-21 09:26
 */
public interface OrderItemDao extends BaseDao<OrderItem> {

    default List<OrderItem> selectListByOrderUuid(String orderUuid) {
        QueryWrapper<OrderItem> wrapper = new QueryWrapper<>();
        wrapper.eq("order_uuid", orderUuid);
        return selectList(wrapper);
    }

    default int selectCountByOrderUuid(String orderUuid) {
        QueryWrapper<OrderItem> wrapper = new QueryWrapper<>();
        wrapper.eq("order_uuid", orderUuid);
        return selectCount(wrapper);
    }

    default List<OrderItem> selectByOrderUuids(Set<String> orderUuids) {
        if (CollectionUtils.isEmpty(orderUuids)) {
            return new ArrayList<>(0);
        }

        QueryWrapper<OrderItem> wrapper = new QueryWrapper<>();
        wrapper.in("order_uuid", orderUuids);
        return selectList(wrapper);
    }

    default int updateRefundStateByUuid(String uuid, ERefundState state, boolean isRefundAtToNull) {
        UpdateWrapper<OrderItem> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("refund_state", state);
        if (isRefundAtToNull) {
            updateWrapper.set("refund_at", null);
        }
        updateWrapper.eq("uuid", uuid);
        return update(null, updateWrapper);
    }

    default Integer findCountByState(EOrderItemState state) {
        QueryWrapper<OrderItem> wrapper = new QueryWrapper<>();
        wrapper.eq("state", state.getValue());
        return selectCount(wrapper);
    }

    @Select({"<script>",
            "SELECT o.uuid FROM o_order_item o ",
            "where o.state = 'DELIVERED' AND o.deliver_at &lt; #{expireDate}",
            "</script>"
    })
    List<String> findExpireReceivedUuids(Date expireDate);

    default List<OrderItem> findByOrderUuid(String orderUuid) {
        return findListByField("order_uuid", orderUuid);
    }
}
